package com.diqizu.servlet.admin;

import java.io.IOException;

import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.diqizu.dao.UserDaoImpl;
import com.diqizu.entity.Users;
import com.diqizu.servlet.BaseServlet;
import com.diqizu.utli.DBManager;
import com.diqizu.utli.QueryDataResult;
import com.diqizu.utli.Result;

/**
 * Servlet implementation class UserServletAdmin
 */
@WebServlet("/admin/UserServletAdmin")
public class UserServletAdmin extends BaseServlet {
	UserDaoImpl userDao = new UserDaoImpl();

	/**
	 * 登录
	 * 
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	public void getUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName = req.getParameter("userName");
		String userPwd = req.getParameter("userPwd");
		String sql = "select * from users where userName='" + userName + "' and userPwd='" + userPwd + "' ";
		System.out.println("ִ�е�sql�����:" + sql);
		QueryDataResult executeQuery = DBManager.execQuery(sql);
		ResultSet rs = executeQuery.rs;
		try {
			if (rs.next()) {
				Users user = new Users();
				user.setUserName(rs.getString("userName"));
				user.setUserPwd(rs.getString("userPwd"));
				user.setUserUrl(rs.getString("userUrl"));
				System.out.println(user);
				HttpSession session = req.getSession();
				session.setAttribute("user", user);// 将数据user存储在session里

				resp.sendRedirect("../admin/index.jsp");
			} else {
				System.out.println("错误");
				resp.sendRedirect("../admin/login.jsp");

			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		executeQuery.close();
	}

	/**
	 * 修改密码
	 * 
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	public void updateUserPwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String mpass = req.getParameter("mpass");
		String renewpass = req.getParameter("renewpass");
		HttpSession session = req.getSession();
		Users a = (Users) session.getAttribute("user");
		boolean res2 = userDao.getUsers(a.getUserName(), mpass);
		PrintWriter out = resp.getWriter(); // ��ȡ�������
		if (res2) {
			boolean res = userDao.updateUsers(renewpass, a.getUserName());
			if (res) {
				out.write(Result.toClient(0, "成功"));
			} else {
				out.write(Result.toClient(1, "失败"));
			}
		} else {
			out.write(Result.toClient(1, "原密码不正确"));
		}
		out.flush();
		out.close();
	}

}
